"""
计算器

Version: 0.1
Author: yuwl
Date：2024-3-31
"""

import tkinter as tk

class Calculator:
    def __init__(self, master):
        self.master = master
        master.title("Simple Calculator")

        # 创建显示结果的文本框
        self.result_var = tk.StringVar()
        self.result_var.set('0')
        self.result_label = tk.Label(master, textvariable=self.result_var, font=('Arial', 20), bg='white', width=12, anchor='e')
        self.result_label.grid(row=0, column=0, columnspan=4, sticky='nsew')

        # 创建按钮
        button_texts = [
            '7', '8', '9', '/',
            '4', '5', '6', '*',
            '1', '2', '3', '-',
            'C', '0', '=', '+'
        ]
        self.buttons = {}
        for index, text in enumerate(button_texts):
            row, col = divmod(index, 4)
            button = tk.Button(master, text=text, font=('Arial', 20), command=lambda t=text: self.on_button_click(t))
            button.grid(row=row+1, column=col, sticky='nsew')
            self.buttons[text] = button

        # 绑定键盘事件
        master.bind('<Key>', self.on_key_press)

    def on_button_click(self, button_text):
        if button_text.isdigit():
            self.append_digit(button_text)
        elif button_text in ['+', '-', '*', '/']:
            self.perform_operation(button_text)
        elif button_text == 'C':
            self.clear()
        elif button_text == '=':
            self.calculate()

    def on_key_press(self, event):
        key = event.char
        if key.isdigit() or key in ['+', '-', '*', '/', '=', 'c', 'C']:
            self.on_button_click(key)

    def append_digit(self, digit):
        current_value = self.result_var.get()
        if current_value == '0':
            self.result_var.set(digit)
        else:
            self.result_var.set(current_value + digit)

    def perform_operation(self, operation):
        self.memory = self.result_var.get()
        self.operation = operation
        self.result_var.set('0')

    def clear(self):
        self.result_var.set('0')
        self.memory = None
        self.operation = None

    def calculate(self):
        if self.memory is not None and self.operation is not None:
            try:
                result = eval(f"{self.memory} {self.operation} {self.result_var.get()}")
                self.result_var.set(str(result))
            except ZeroDivisionError:
                self.result_var.set("Error")
            except Exception as e:
                self.result_var.set("Error")
            self.memory = None
            self.operation = None

# 创建主窗口
root = tk.Tk()
# 创建计算器实例
calculator = Calculator(root)

# 设置网格的权重，使列和行可以扩展
for i in range(4):
    root.grid_rowconfigure(i, weight=1)
    root.grid_columnconfigure(i, weight=1)

# 运行主循环
root.mainloop()
